import Range from './core/Range';
import styles from './marker.css.js';

function addUnderline() {
  replaceSelectedStrByEle(styles['custom-underline']);
}

/**
 * 启用荧光笔
 */
function enableNiteWriterPen() {
  replaceSelectedStrByEle(styles['nite-writer-pen']);
}

/**
 * 用元素替换被选中的文本
 */
function replaceSelectedStrByEle(className) {
  var getRange = () => {
    var me = window;
    var range = new Range(me.document);

    var sel = window.getSelection();
    if (sel && sel.rangeCount) {
      var firstRange = sel.getRangeAt(0);
      var lastRange = sel.getRangeAt(sel.rangeCount - 1);
      range
        .setStart(firstRange.startContainer, firstRange.startOffset)
        .setEnd(lastRange.endContainer, lastRange.endOffset);
    }
    return range;
  };
  var range = getRange();
  range.applyInlineStyle('i', {
    class: className,
  });
  range.select();
}

window.document.addEventListener('mouseup', function (event) {
  const selObj = window.getSelection();
  const { isCollapsed } = selObj;
  if (isCollapsed) {
    return;
  }
  const range = selObj.getRangeAt(0);
  console.log('styles-->',styles)
  setTimeout(()=>{
    enableNiteWriterPen()
    addUnderline()
  },2000)
});
